package com.chenxin.transaction.service.impl;

import com.chenxin.transaction.dao.AccountInfoDao;
import com.chenxin.transaction.feign.LisiFeign;
import com.chenxin.transaction.service.AccountInfoService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 210623m
 */
@Service
@Slf4j
public class AccountInfoServiceImpl implements AccountInfoService {

    @Autowired
    private AccountInfoDao accountInfoDao;

    @Autowired
    private LisiFeign lisiFeign;

    /**
     * 实施转账业务:
     *
     * @param accountNo
     * @param amount
     */
    @Transactional
    @GlobalTransactional
    public void updateAccountBalance(String accountNo, Double amount) {
        log.info("zhangsan 转账生成的全局事务id是：{}", RootContext.getXID());
        //先扣减张三的金额
        accountInfoDao.updateAccountBalance("1", amount * -1);
        //李四增加金额
        String transfer = lisiFeign.transfer(amount);
        if ("fail to invoke".equals(transfer)) {
            throw new RuntimeException("调用李四微服务转账异常！！");
        }
        //模拟张三扣钱后，调用李四的服务出现异常
        if(amount == 2){
            throw new RuntimeException("张三转账李四异常！！");
        }
    }
}
